import socket
from tqdm import tqdm
import errno

def is_port_open(ip, port):
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(1)
        result = sock.connect_ex((ip, port))
        if result == 0:
            print(f"Port {port} is open on {ip}")
        else:
            if result == errno.ECONNREFUSED:
                print(f"\nPort {port} is closed on {ip} (connection refused)")
            elif result == errno.ETIMEDOUT:
                print(f"\nPort {port} is closed on {ip} (connection timed out)")
            elif result == errno.ENETUNREACH:
                print(f"\nNetwork unreachable when trying to reach {ip}")
            elif result == errno.EHOSTUNREACH:
                print(f"\nHost unreachable when trying to reach {ip}")
            else:
                print(f"\nPort {port} is closed on {ip} (error {result})")
        sock.close()
    except Exception as e:
        print(f"Error: {e}")

def scan_ports(ip, start_port, end_port):
    for port in tqdm(range(start_port, end_port + 1), desc="Scanning ports", unit="port"):
        is_port_open(ip, port)

if __name__ == "__main__":
    target_ip = "127.0.0.1"
    start_port = 120
    end_port = 136
    scan_ports(target_ip, start_port, end_port)
